package com.yf.system.utils;

import com.coremedia.iso.IsoFile;
import com.yf.ability.upload.providers.local.config.LocalConfig;
import com.yf.ability.upload.providers.local.service.LocalUpService;
import com.yf.base.utils.ResourceUtil;
import com.yf.base.utils.file.MD5Util;

import lombok.extern.log4j.Log4j2;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.IOException;
import java.net.URL;

/**
 * 视频工具，获取视频文件大小
 */
@Log4j2
@Component
public class VideoUtil {

    @Autowired
    private LocalUpService localUpService;

    /**
     * 获取视频文件的播放长度(mp4、mov格式)
     * @param url
     * @return 单位为毫秒
     */
    public long getDuration(String url) {

        String filePath = "";

        try {

            // 网络文件先下载
            if (url.startsWith("http") || url.startsWith("https")) {
                // 临时文件
                filePath = ResourceUtil.tempDir(true) + MD5Util.MD5(url);
                File file = new File(filePath);
                FileUtils.copyURLToFile(new URL(url), file);
            } else {
                // 本地文件
                LocalConfig config = localUpService.getConfig();
                filePath = config.getLocalDir() + url;
            }


            System.out.println("+++++获取视频时长："+filePath);

            File file = new File(filePath);
            if (!file.exists()) {
                return 0;
            }
            return this.getVideoDuration(filePath);

        }catch (Exception e){
            log.error(e);
            return 0;
        }
    }

    /**
     * 是
     * @param videoPath
     * @return
     * @throws IOException
     */
    public long getVideoDuration(String videoPath) throws IOException {
        IsoFile isoFile = new IsoFile(videoPath);
        long lengthInSeconds = isoFile.getMovieBox().getMovieHeaderBox().getDuration() / isoFile.getMovieBox().getMovieHeaderBox().getTimescale();

        // 关闭
        isoFile.close();
        // 删除文件
        File file = new File(videoPath);
        file.delete();
        return lengthInSeconds;
    }



}
